<?php
namespace Home\Controller;

use Think\Controller;
// use Think\Exception;
require(dirname(dirname(__FILE__))."/ORG/wx/wxBizMsgCrypt.class.php");
/**
 * @name 前端入口controller
 * @author perry
 * @version 1.0 2015-07-30
 */
class IndexController extends Controller {

	public function checkAllPicUsed(){
        //轮询检查所有图片上会否还在被使用
        // $ckey='MultiUploadPic_checkAllPicUsed'.$_GET['type'];
        // $lastCheckTime=S($ckey);
        // if(!$lastCheckTime){
        //    $lastCheckTime=time()-65536; 
        // }
        // if(time()-$lastCheckTime>300){
            $picM=D('Admin/MultiUploadPic');
            $picM->checkAllPicUsed("",$_GET['seconds'],$_GET['count']);
            // S($ckey,time());
        // }
        //end 先实时检查所有图片上会否还在被使用
    }

	
	function _initialize(){
		$this->checkToken=C('third_check_token');
		$this->checkKey=C('third_check_key');
		$this->thirdAppid=C('third_app_id');
		//debug decryptMsg
		// $sdkCrypt = new \Home\ORG\wx\WXBizMsgCrypt($this->checkToken,$this->checkKey,$this->thirdAppid);
  //       $msg='';
  //       $postStr='<xml>
		//     <AppId><![CDATA[wxd3e99abc1a62d1b5]]></AppId>
		//     <Encrypt><![CDATA[S2aPc4gRWIb9MRrBisjYbr9XnGLJSFp+npAM3q4sMSv+GLG8dg/sXQ0qkCawUmAuo2v1ZQyMR3R10BS11W+uoK6XdVIW2T45xqglRVxDXbrrcHBx/OwDX/iu7xjN3mS57qiygfr/gSYGQvzmtRm8H4x1xoSpDaP4Vo6S+aDXlpT82Q2ak2wPFIuRnSZvl0CrY0ec9jbm3uhCF5YyWWBt3bfbOAZglJP9uR8i1wj3DzMT4FTX+5E9S+EuJXc+406MVVLRicBzbKbHAtl1z91jmYaEjjHObinP3/CdSDP/ypnHmE+3vKLQDoENfckZDNGpdgLnb/XSnaMlTlpdq8FpZY8azysy1uNOJ5fZZ1eZI9AoFNt/PYftPw7YodOSI6LmlO21WH5gL+qXgxd+T6OzlRhgNMwD0Ys4Al+D4+qnjtldUWhtsXY4zN/ZsceHh4T1zm+YZTwB2oX3hE5peXmeIQ==]]></Encrypt>
		// </xml>';
  //       $re=$sdkCrypt->decryptMsg('6e74b2ecee13e1906f15430289ff24c90d91acf0', '1488260084', '1091765791', $postStr, $msg);
  //       dump($re);
  //       dump($msg);
  //       $aa=xmlToArray($msg);
  //       dump($aa);
  //       dump($aa['ComponentVerifyTicket']);
  //       if(array_key_exists('InfoType', $aa)){
  //       	call_user_func(array($this,$aa['InfoType']),$aa);
  //       }
  //       exit;
		//end debug
	}

	// public function index() {
	// 	// $weixin_user = $_SESSION[C('weixin_session_key')];
	// 	// header("Content-type: text/html; charset=utf-8");
	// 	echo($weixin_user['nickname'].',welcome to 首页.');
	// 	// $redirectUrl='http://' . $_SERVER['HTTP_HOST'].'/Home/Userindex/index';
	// 	// header("location: ".$redirectUrl,true,301);
	// }

	//授权事件接收URL
	public function authevent(){
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        if(!$postStr){
        	// echo 'emtpy';
        	// M('weixin_xml')->data(array('create_time' => time(), 'content' => 'empty'))->add(); //保存数据
        	return;
        }
        $sdkCrypt = new \Home\ORG\wx\WXBizMsgCrypt($this->checkToken,$this->checkKey,$this->thirdAppid);
        $msg='';
        $re=$sdkCrypt->decryptMsg($_REQUEST['msg_signature'], $_REQUEST['timestamp'], $_REQUEST['nonce'], $postStr, $msg);
        if($re!=0){
        	//解密失败了
        	return;
        }
        $request_info=json_encode($_REQUEST);
        M('weixin_xml')->data(array('create_time' => time(), 'content' => $postStr.$request_info,'decrypt_content'=>$msg))->add(); //保存数据
        $postArr=xmlToArray($msg);
        if(array_key_exists('InfoType', $postArr)){
        	call_user_func(array($this,$postArr['InfoType']),$postArr);
        }
        echo "success";
	}

	//微信component_verify_ticket事件推送 每10分钟一次
	private function component_verify_ticket($postArr){
		$m=D('Home/ComponentVerifyTicket');
		$m->addOne($postArr);
	}

	//微信 公众号取消对三方平台的授权通知
	private function unauthorized($postArr){
		$m=D('Home/AuthorizationInfo');
		$m->unauthorized($postArr);
	}

	//微信 公众号对三方平台的授权陈宫通知
	private function authorized($postArr){
		$m=D('Home/AuthorizationInfo');
		$m->authorized($postArr);
	}

	////微信 公众号对三方平台的授权更新通知
	private function updateauthorized($postArr){
		$this->authorized($postArr);
	}
	//前端提交接口
	public function insertSubmit(){
		try {
			$wx_user_id = $_SESSION['weixin_user_auth5']['id'];
	        $redirect_url = C('login_url');
			if(empty($wx_user_id)){
				$this->customReturn(0,array('errmsg'=>"您还没有登录，即将为你跳转登录.",'redirect_url'=>$redirect_url));
				header('location:' . $redirect_url);
			}
			$datalist = array();
			$datalistAnwer = array();
			$datalist['phone'] = I('phone');
			$datalist['realname'] = I('realname');
			$datalist['address'] = I('address');
			$datalist['update_time'] = time();
			$options = I('options');
			$str_options = implode(',', $options);
			$datalistAnwer['options'] = $str_options;
			$datalistAnwer['user_id'] = $wx_user_id;
			$anwer = array('F','E','D','C','A','B');
			$fenzhi = 0;
			if(empty($datalistAnwer['options'])){
				throw new \Exception("网络不通答案提交失败", -6);
			}
			if(count($options) < 6){
				throw new \Exception("答案没有全部填完", -56);
			}
			for ($i=0; $i < count($options); $i++) {
				if($options[$i] == $anwer[$i]){
					$fenzhi ++;
				}			
			}
			$datalistAnwer['score'] = $fenzhi;
			if(empty($datalist['address'])){
				throw new \Exception("地址为空", -1);
			}
			if(empty($datalist['realname'])){
				throw new \Exception("姓名为空", -2);
			}
			if(empty($datalist['phone'])){
				throw new Exception("手机号为空", -3);
				
			}
			if(!ic_isCellPhone($datalist['phone'])){
				throw new \Exception("手机号格式不正确", -5);
			}
			$isCunZai=M('weixin_user')->where(array('id'=>$wx_user_id))->getField($phone);
			if($isCunZai == $datalist['phone']){
				throw new \Exception("该手机号已被使用，提交失败", -11);
			}
			$res = M('weixin_user')->where(array('id'=>$wx_user_id))->save($datalist);
			if($res){
				$an_user_id = M('fotile520_option')->where(array('user_id'=>$wx_user_id))->find();
				if($an_user_id){
					throw new \Exception("你已提交过信息，不能重复提交", -12);
					// M('fotile520_option')->where(array('id'=>$an_user_id['id']))->save($datalistAnwer);
				}else{
					
					$resanwer = M('fotile520_option')->add($datalistAnwer);
				}
				$this->customReturn(1,$res,'提交成功');
			}
		} catch (\Exception $ecx) {
			 $this->customReturn(-400, array('errmsg' => $ecx->getMessage(), 'errcode' =>'-400'));
		}
	}
	public function customReturn($status, $content)
    {
        $data['succ'] = $status;
        if (!$content) {
            $content = array();
        }
        $data['data'] = $content;
        //$this->ajaxReturn($data);
        // echo (json_encode($data,JSON_UNESCAPED_SLASHES));
        echo str_replace("\\/", "/", json_encode($data));
        exit;
    }

}
